(function () {
    'use strict';
    var msg = Message.setting;
    var debug = Message.debug;
    var setting = angular.module('feibo.setting.controller');
    setting.controller('UserManageCtr', userManage)
        .controller('SchoolListCtr', schoolList)
        .controller('schoolProfileCtr', schoolProfile)
        .controller('SinglePersonInfoCtr', singlePersonInfo)
        .controller('noticeCtr', notice)
        .controller('upphotoCtr', upphoto)
        .controller('actionEmailCtr', actionEmail)
        .controller('agencyCtr', agencyManage)

    userManage.$inject = ['$scope', 'UserManageService', 'SchoolListService', 'CommonService', '$timeout', 'kvMap',
                          'valiFrom', 'StudentService'];
    agencyManage.$inject = ['$scope', 'UserService', 'SchoolService','SchoolListService', 'CommonService', '$timeout',
                            'kvMap', 'valiFrom', '$state'];

    schoolList.$inject =
        schoolProfile.$inject = ['$scope', '$filter', 'SchoolListService', 'UserManageService', 'valiFrom',
                                 'feiboDrees', '$timeout'];

    singlePersonInfo.$inject = ['$scope', 'UserManageService', 'valiFrom', 'CommonService', '$timeout', '$interval'];

    notice.$inject = ['$scope', 'NoticeService', 'UserManageService'];

    upphoto.$inject = ['$scope', 'UserManageService', 'CommonService', '$filter'];

    actionEmail.$inject = ['$scope', 'UserManageService', '$stateParams', '$state'];
    //个人信息设置

    function singlePersonInfo($scope, userservice, valiFrom, CommonService, $timeout, $interval) {
        $scope.getpersoninfo = function () {
            userservice.getUserById($scope.data.userInfo.id).then(function (res) {
                if (res.data.success) {
                    var rd = res.data.data;
                    $scope.data.fromData = {
                        nickname: rd.nickname,
                        gender: rd.gender,
                        email: rd.email,
                        cellphone: rd.cellphone,
                        id: rd.id,
                        qq: rd.qq,
                        username: rd.username,
                        object_pk: rd.object_pk,
                        valid_cellphone: rd.valid_cellphone,
                        valid_email: rd.valid_email,
                        emailValiText: rd.valid_email ? '已验证' : '未验证',
                        cellValiText: rd.valid_cellphone ? '已验证' : '未验证',
                    };
                    $timeout(function () {
                        $scope.isSave = true;
                    }, 200);
                } else {
                    layer.msg(msg.personInfo.getUserinfoErr, {
                        'icon': 2
                    });
                }
            });
        };


        $scope.queryInit = function () {
            valiFrom.extenUniqueVali('uniqueEmail');
            valiFrom.extenUniqueVali('uniqueCellphone');
            valiFrom.addVali($scope.data.valigroup, $scope.saveUserInfo);
            valiFrom.addVali($scope.data.valimodal, $scope.fromSub);
            feiboCommonFuncs.initModal($scope.data.modalqs.id, function () {
                valiFrom.resetVali($scope.data.modalqs.id, $scope.data.modalqs.errid);
                $scope.data.ydGtConfig.refresh();
                $('#cellphone').val($scope.data.fromData.cellphone);
            });
        };


        $scope.modal = function (type) {
            var sd = $scope.data;
            if (type === 'close') {
                feiboCommonFuncs.hideModal(sd.modalqs.id);
            } else {
                if ($scope.isSave) {
                    sd.modal = msg.personInfo.modal[type];
                    if (type === 'cellphone') {
                        sd.modal.title = '验证手机';
                    }
                    sd.modalType = type;
                    feiboCommonFuncs.showModal(sd.modalqs.id);
                } else {
                    layer.msg(msg.personInfo.saveErr, {
                        'icon': 2
                    });
                }

            }
        };


        $scope.fromSub = function () {
            var sd = $scope.data;
            var sdf = sd.fromData;
            if (sd.modalType === 'cellphone') {
                userservice.valiCellphoe(sdf.object_pk, sdf.cellphone, sdf.valiCellCode).then(function (res) {
                    if (res.data.success) {
                        layer.msg(msg.personInfo.valiCell.Suc, {
                            'icon': 1
                        });
                        $scope.getpersoninfo();
                        $scope.modal('close');
                    } else {
                        layer.msg(msg.personInfo.valiCell.Err, {
                            'icon': 2
                        });
                    }
                });
            }
            if (sd.modalType === 'rspwd') {
                userservice.rePwd(sdf.id, sdf.newPwd).then(function (res) {
                    if (res.data.success) {
                        layer.msg(msg.personInfo.rePwd.Suc, {
                            'icon': 1
                        });
                        $scope.modal('close');
                    } else {
                        layer.msg(msg.personInfo.rePwd.Err, {
                            'icon': 2
                        });
                    }
                });
            }
        };


        $scope.getCellValiCode = function () {
            var sdf = $scope.data.fromData;

            $scope.data.countdowntime.cellvalue = 60;
            $scope.data.countdowntime.celldisable = true;
            var timercell = $interval(function () {
                $scope.data.countdowntime.cellvalue -= 1;
            }, 1000, $scope.data.countdowntime.cellvalue);
            timercell.then(function () {
                $scope.data.countdowntime.cellinit();
            }, function () {
                $scope.data.countdowntime.cellinit();
            });

            if ($scope.data.fromData.cellphone) {
                CommonService.valiCellPhoeunique(sdf.cellphone, sdf.id).then(function (res) {
                    if (res.data.validata) {
                        return userservice.getCellValiCode(sdf.object_pk, sdf.cellphone);
                    } else {
                        $interval.cancel(timercell);
                        valiFrom.addError($scope.data.valimodal.formId, ['您输入的手机号已被使用，请确保手机的唯一性']);
                    }
                }).then(function (res) {
                    if (res) {
                        if (res.data.success) {
                            $scope.getpersoninfo();
                            layer.msg(msg.personInfo.sendCellCode.Suc, {
                                'icon': 1
                            });
                        } else {
                            $interval.cancel(timercell);
                            layer.msg(msg.personInfo.sendCellCode.Err, {
                                'icon': 2
                            });
                        }
                    }
                });
            }
        };


        $scope.valiEmai = function () {
            var sdf = $scope.data.fromData;

            $scope.data.countdowntime.emailvalue = 60;
            $scope.data.countdowntime.emaildisable = true;
            var timer = $interval(function () {
                $scope.data.countdowntime.emailvalue -= 1;
            }, 1000, $scope.data.countdowntime.emailvalue);
            timer.then(function () {
                $scope.data.countdowntime.emailinit();
            }, function () {
                $scope.data.countdowntime.emailinit();
            });

            if (sdf.email) {
                CommonService.valiEmailunique(sdf.email, sdf.id).then(function (res) {
                    if (res.data.success && res.data.validata) {
                        return userservice.valiEmail(sdf.object_pk, sdf.email);
                    } else {
                        $interval.cancel(timer);
                        valiFrom.addError($scope.data.valigroup.formId, ['您输入的邮箱已被使用，请确保邮箱的唯一性']);
                    }
                }).then(function (res) {
                    if (res) {
                        if (res.data.success) {
                            layer.msg(msg.personInfo.valiEmail.Suc, {
                                'icon': 1
                            });
                        } else {
                            $interval.cancel(timer);
                            layer.msg(msg.personInfo.valiEmail.Err, {
                                'icon': 2
                            });
                        }
                    }
                });
            } else {
                layer.msg(msg.personInfo.saveErr, {
                    'icon': 2
                });
            }
        };


        $scope.saveUserInfo = function () {
            var fd = $scope.data.fromData;
            var params = {
                nickname: fd.nickname,
                gender: fd.gender,
                qq: fd.qq,
                email: fd.email,
                cellphone: fd.cellphone
            };
            userservice.editUser(params, fd.id).then(function (res) {
                if (res.data.success) {
                    $scope.getpersoninfo();
                    layer.msg(msg.personInfo.edit.Suc, {
                        'icon': 1
                    });
                } else {
                    layer.msg(msg.personInfo.edit.Err, {
                        'icon': 2
                    });
                }
            });
        };


        $scope.data = {
            isSave: true,
            countdowntime: {
                cellvalue: '发送手机验证码',
                celldisable: false,
                emailvalue: '验证邮箱',
                emaildisable: false,
                emailinit: function () {
                    this.emailvalue = '验证邮箱';
                    this.emaildisable = false;
                },
                cellinit: function () {
                    this.cellvalue = '发送手机验证码';
                    this.celldisable = false;
                },
            },
            userinfo: {},
            valigroup: {
                formId: 'setting-personinfo',
                group: 'setting',
                scope: 'personInfo'
            },
            valimodal: {
                formId: 'personinfo-modal-form',
                group: 'setting',
                scope: 'personInfoModal'
            },
            modalqs: {
                id: 'setting-personinfo-modal',
                errid: 'modal-form-error'
            },
            fromData: {},
            modal: {},
            modalType: '',
            modalData: {},
            ydGtConfig: {
                validateData: {},
                loadChallenge: function (create) {
                    CommonService.getCaptcha().then(function (res) {
                        if (res.data.success) {
                            create({
                                gt: res.data.gt,
                                challenge: res.data.challenge
                            });
                        }
                    });
                }
            }
        };


        $scope.init = function () {
            userservice.getuserinfo().then(function (res) {
                $scope.data.userInfo = res.data.data;
                $scope.getpersoninfo();
            });
            $scope.queryInit();
        };
        $scope.init();
        $('.fb-navigation').removeClass('active');
        $('#account-settings').addClass('active');
    }


    //用户管理
    function userManage($scope, userservice, schoolservice, CommonService, timeout, kvMap, valiFrom, StudentService) {
        $scope.data = {
            nickname: undefined,
            searchSchoolId: undefined,
            role: undefined,
            schoolListid: [],
            valigroup: {
                formId: 'setting-userManage-from',
                group: 'setting',
                scope: 'userManage'
            },
            userrole: undefined,
            mgrRoleLogin: undefined,
            personInfo: {},
            userlist: {},
            userdata: {},
            usermodal: {
                onHidden: function () {
                    $scope.data.userdata = {};
                    valiFrom.resetVali($scope.data.valigroup.formId);
                }
            },
            schoolList: [],
            gender: kvMap.gender,
            paginate: {
                itemsPerPage: 15,
                currentPage: 1
            },
            title: '添加',
            init: function(){
                  // var roleKvMap = kvMap.role.vkMap;
                  // var studentMgr = roleKvMap.studentMgr;
                  // var schoolMgr =  roleKvMap.schoolMgr;
                  // this.userdata.role = schoolMgr;
                  // this.userrole[studentMgr] = 'Student Manager';
                  // this.userrole[schoolMgr] = 'School Manager';
                  this.userrole = CommonService.cloneMapping(kvMap.role, ['3','4','vkMap']); //去掉Teacher Student
                  this.mgrRoleLogin = kvMap.role.vkMap; // schoolMgr, studentMgr
                  return this;
            }
        }.init();


        $scope.init = function () {
            var initshool = {};
            userservice.getuserinfo().then(function (res) {
                if (res.data.success) {
                    $scope.data.personInfo = res.data.data;
                    initshool = {
                        pk: res.data.data.school_id,
                        name: res.data.data.school_name
                    };
                    return schoolservice.getshoolList({
                        parent_id: res.data.data.school_id
                    });
                }
            }).then(function (res) {
                res.data.data.push(initshool);
                //$scope.data.schoolList = res.data.data;
                angular.forEach(res.data.data, function (data) {
                    $scope.data.schoolListid.push(data.pk);
                });
                $scope.getUserList();
                $scope.initSemanticInstantSearch();
                $scope.queryInit();
            });

        };

        $scope.initSemanticInstantSearch = function(){
            var suc = function(){
                $scope.data.userdata.school_id = $scope.data.school_id;
            };
            CommonService.semanticInstantSearch({
                  url: ENDPOINTS.school.search + '?page_size=10&search={query}',
                  cssId: 'search-subschool',
                  container: $scope.data,
                  propName: 'school_id',
                  propChain: ['entries'],
                  resultsPropsConfig: {
                      title: ['name'],
                      value: ['id']
                  },
                  callback: suc
               });
        };

        $scope.queryInit = function () {
            valiFrom.extenUniqueVali('uniqueUsername');
            valiFrom.extenUniqueVali('uniqueCellphone');
            valiFrom.extenUniqueVali('uniqueEmail');
            valiFrom.addVali($scope.data.valigroup);
        };

        $scope.getUserList = function () {
            var _vd = $scope.data;
            var suc = function (res) {
                if (res.data.success) {
                    var tmp = res.data.data;
                    var currentUserId = $scope.data.personInfo.id;
                    _vd.userlist = tmp.entries.filter(function(currentElement){
                            return currentElement.id !== currentUserId;
                    });
                    _vd.paginate.currentPage = tmp.pageNo;
                    CommonService.paginate(
                        'material-paginate-list',
                        _vd.paginate.currentPage,
                        tmp.pageCount,
                        function (loadingPageIndex) {
                            $scope.data.paginate.currentPage = loadingPageIndex;
                            $scope.getUserList();
                        }
                    );
                    feiboCommonFuncs.showMoreulli('more');
                } else {
                    layer.msg(msg.user.fetchListErr, {
                        'icon': 2
                    });
                }
            };
            var parma = {
                page: _vd.paginate.currentPage,
                page_size: _vd.paginate.itemsPerPage,
                nickname: $scope.data.nickname,
                school: $scope.data.searchSchoolId,
                role: $scope.data.role
            };
            if ($scope.data.role == 0) {
                parma.role = Object.keys(CommonService.cloneMapping(kvMap.role, ['3','4','vkMap'])).join();
            }
            userservice.getUserList(parma).then(suc);
        };

        $scope.initSearch = {
            searchSchool: {
                url: ENDPOINTS.school.search + '?page_size=10&search={query}',
                container: $scope.data,
                propName: 'searchSchoolId',
                propChain: ['entries'],
                resultsPropsConfig: {
                    title: ['prefix', 'name'],
                    value: ['id']
                },
                callback: $scope.getUserList,
                clearCallback: true
            }
        };

        $scope.initDropdown = function(cssId){
            $('#' + cssId).dropdown();
            timeout(function(){
                $('#' + cssId).dropdown('set selected', '0');
            }, 0);
        };

        $scope.loginCenter = function(user){
            var queryConfig = {
                funcName: 'loginCenter',
                errorMsg: '登录失败',
                propChain: [],
                httpGetParams: {
                    pk: user.object_pk
                }
            };

            StudentService.loginLearncenter(queryConfig).then(function(returnedData){
                if(returnedData.success){
                    var winOpen = window.open(returnedData.data.url);
                    if(winOpen === null){
                        var $tips = $('#tips-go-center');
                        $scope.data.schoolName = user.school_region.name || user.school.name;
                        $tips.find('a').attr('href', returnedData.data.url);
                        $tips.modal('show');
                    }
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        $scope.delUser = function (pk) {
            var suc = function (res) {
                if (res.data.success) {
                    layer.msg(msg.user.delSuc, {
                        'icon': 1
                    });
                    $scope.getUserList();
                } else {
                    layer.msg(msg.user.delErr, {
                        'icon': 2
                    });
                }
            };
            layer.confirm('您确认要删除吗？', {
                btn: ['确定', '取消']
            }, function () {
                userservice.delUser(pk).then(suc);
            });
        };

        $scope.setDefaultRoleSelected = function(){
            $('#dropdown-role').dropdown();
            timeout(function () {
                $('#dropdown-role').dropdown('set selected', '');
            }, 0);
        };


        $scope.modal = function (cz, ud) {
            if (cz === 'add') {
                $scope.data.userdata = {
                    school_id: '',
                    qq: '',
                    password: '',
                    gender: '',
                    role: ''
                };
                $scope.data.pwd = true;
                $scope.data.title = '添加';
                $("#pwd").attr('disabled', false);
            }
            if (cz === 'edit') {
                $scope.data.pwd = false;
                $scope.data.title = '编辑';
                $("#pwd").attr('disabled', true);
                $scope.data.userdata = {
                    school_id: ud.school_id,
                    role: ud.role,
                    username: ud.username,
                    email: ud.email,
                    nickname: ud.nickname,
                    cellphone: ud.cellphone,
                    qq: ud.qq,
                    gender: String(ud.gender),
                    id: ud.id
                };
            }
            $scope.data.schoolName = ud&&ud.school.name || '';
            timeout(function () {
                $('.ui.dropdown.gender').dropdown('set text', '');
                $('.ui.dropdown.role').dropdown('set text', '');
                $('.ui.dropdown.gender').dropdown('set selected', ud&&ud.gender || '');
                //$('.ui.dropdown.school_id').dropdown('set text', ud&&ud.school.name || '');
                $('.ui.dropdown.role').dropdown('set selected', ud&&ud.role || '');
            });
            $scope.data.stlyle = {
                'display': 'none'
            };
            if (cz === 'close') {
                $scope.data.usermodal.hide();
            } else {
                $scope.data.usermodal.show();
            }
        };
        $('.close_modal').on('click',function(){
            $('#setting-userManage,.modal_grey').fadeOut();
        });


        $scope.saveUser = function () {
            if (valiFrom.getVali($scope.data.valigroup.formId)) {
                var czmsg = {
                    suc: msg.user.addSuc,
                    err: msg.user.addErr
                };
                var suc = function (res) {
                    if (res.data.success) {
                        layer.msg(czmsg.suc, {
                            'icon': 1
                        });
                        $scope.getUserList();
                        $scope.modal('close');
                    } else {
                        layer.msg(czmsg.err, {
                            'icon': 2
                        });
                    }
                };
                if ($scope.data.userdata.id) {
                    czmsg = {
                        suc: msg.user.editSuc,
                        err: msg.user.editErr
                    };
                    userservice.editUser($scope.data.userdata, $scope.data.userdata.id).then(suc);
                } else {
                    if(!$scope.data.userdata.role){
                        $scope.data.userdata.role = kvMap.role.vkMap.schoolMgr;
                    }
                    userservice.addUser($scope.data.userdata).then(suc);
                }
            } else {
                $scope.data.stlyle = {
                    'display': 'block'
                };
            }
        };


        $scope.init();
    }




    // 机构管理
     function agencyManage($scope, userservice, SchoolService, SchoolListService, CommonService, timeout, kvMap, valiFrom, $state) {
         $scope.data = {
            schoolList: [],
            pagenate: {
                page_size: 999,
                page: 1
            },
            school_id: '',
            search: '',
            cus_service_id: '',
            create: {
                httpPostData: {
                    name: '',
                    prefix: '',
                    number: '',
                    archive_number: '',
                    address: '',
                }
            }
        };
         $scope.users = {};
         $scope.init = function(){
                $scope.getSchool();
                $scope.getOperate();
                $scope.getAgnencyType();
         };
         $scope.getSchool = function () {
             if ($scope.data.school_type_id == 0) {
                 $scope.data.school_type_id = '';
             }
             if ($scope.data.cus_service_id == 0) {
                 $scope.data.cus_service_id = '';
             }
             var queryConfig = {
                    container: $scope.data,
                    propName: 'schoolList',
                    funcName: 'getSchool',
                    propChain: ['data'],
                    showLoadLayer: false,
                    httpGetParams: {
                        page: $scope.data.pagenate.page,
                        page_size: $scope.data.pagenate.page_size,
                        cus_service_id: $scope.data.cus_service_id,
                        school_type_id: $scope.data.school_type_id,
                        search: $scope.data.search
                    }
                };
             SchoolService.getStatisticSchool(queryConfig).then(function(res){
                 //CommonService.paginate(
                 //       'material-paginate-list',
                 //       $scope.data.pagenate.page,
                 //       res.pages.pageCount,
                 //       function (loadingPageIndex) {
                 //           $scope.data.pagenate.page = loadingPageIndex;
                 //           $scope.getSchool();
                 //       }
                 //   );
             })


        };

         $scope.initDropdown = function(arg){
                    $('.ui.dropdown').dropdown();

                };

         $scope.getOperate = function(){
                var queryConfig = {
                    container: $scope.users,
                    propName: 'userList',
                    funcName: 'getOperate',
                    propChain: ['data','entries'],
                    showLoadLayer: false,
                    httpGetParams: {
                        page: 1,
                        page_size: 999,
                        role: 8
                    }
                };
             userservice.fetchUsers(queryConfig).catch(function(err){
                 console.log(err)
             })
         };
// 获取机构类别
         $scope.getAgnencyType = function(){
            var queryConfig = {
                container: $scope.data,
                propChain: ['data','entries'],
                funcName: 'getAgnencyType',
                showLoadLayer: false,
                propName: 'typeList'
            }
            SchoolService.getSchoolType(queryConfig);
         };
         $scope.delSchool = function(id){
              var deleteConfig = {
                        container: $scope.data,
                        propChain: ['data'],
                        funcName: 'deleteConfig',
                        propName: '',
                        successMsg:'删除机构成功！',
                        errorMsg:'删除机构失败！',
                        showLoadLayer: false,
                        urlPlaceholder: {
                            schoolId: id
                        }
                    }
                   layer.confirm('您确认要删除吗？', {
                        btn: ['确定', '取消'] //按钮
                    }, function (index) {
                        SchoolService.delSchool(deleteConfig).then(function(){
                            layer.close(index);
                            $scope.getSchool();
                        });
                    });

         };
// 获取机构相关统计
        // $scope.fetchStatistic = function(id){
        //     var now =''
        //     var date = new Date();
        //     var y = date.getFullYear();
        //     var m = date.getMonth()+1;
        //     var d = date.getDate();
        //     now += y +'-' + m + '-' + d;
        //     var queryConfig = {
        //             container: $scope.data,
        //             propChain: ['data'],
        //             funcName: 'fetchStatistic',
        //             propName: 'statisticInfo',
        //             httpGetParams: {
        //                 start_time: now
        //             },
        //             urlPlaceholder: {
        //                 id: id
        //             }
        //         }
        //     SchoolService.getStatistic(queryConfig);
        // };


 $scope.addNewSchool = function(){
        var postConfig = {
                container: $scope.data,
                propChain: ['data'],
                funcName: 'addNewSchool',
                propName: '',
                showLoadLayer: false,
                successMsg:'添加机构成功！',
                errorMsg:'添加机构失败！',
                httpPostData: $scope.data.create.httpPostData
            }
            SchoolService.addSchool(postConfig).then(function (res) {
                    if (res.success) {
                        $('#addSchool').modal('hide');
                        $scope.getSchool();
                    }
                });
    };
    valiFrom.extenUniqueVali('uniqueNumber');
    valiFrom.extenUniqueVali('uniquePrefix');

$('#addSchoolForm').form({
    fields: {
        nickname: {
            rules: [{
                type: 'empty',
                prompt: '请输入机构名称'
            }]
        },
        prefix: {
            rules: [{
                type: 'empty',
                prompt: '请输入机构学号前缀'
            },
            {
                type: 'uniquePrefix',
                prompt: '学号前缀已被使用,请重新输入一个未被使用的前缀，确保学号前缀的唯一性'
            }]
        },
        number: {
            rules: [{
                type: 'empty',
                prompt: '请输入机构编号'
            },
            {
                type: 'uniqueNumber',
                prompt: '该编号已被使用,请重新输入一个编号'
            }]
        },
    },
    onSuccess: function(){
        $scope.addNewSchool();
        return false;
    }
});

    }
// 添加机构













































    //分校区
    function schoolList($scope, $filter, schoolservice, userservice, valiFrom, feiboDrees, $timeout) {
        $scope.data = {
            shoolList: [],
            pagenate: {
                itemsPerPage: 100,
                currentPage: 1
            },
            modeltitle: '添加',
            userInfo: {},
            schoolForm: {},
            valigroup: {
                formId: 'setting-schoolList',
                group: 'setting',
                scope: 'schoolList'
            },
            schoolmodal: {
                onHidden: function () {
                    $scope.data.schoolForm = {};
                    valiFrom.resetVali($scope.data.valigroup.formId);
                }
            }
        };


        $scope.division = feiboDrees;


        $scope.init = function () {
            userservice.getuserinfo().then(function (res) {
                if (res.data.success) {
                    $scope.data.userInfo = res.data.data;
                    //$scope.getShoolList();
                } else {
                    layer.msg(msg.user.fetLoginInfo, {
                        'icon': 2
                    });
                }
            });
            $scope.queryInit();
        };


        $scope.queryInit = function () {
            valiFrom.extenUniqueVali('uniqueNumber');
            valiFrom.extenUniqueVali('uniquePrefix');
            valiFrom.addVali($scope.data.valigroup);
        };


        $scope.getShoolList = function () {
            var param = $scope.data.pagenate;
            param.parent_id = $scope.data.userInfo.school_id;
            var suc = function (res) {
                if (res.data.success) {
                    $scope.data.shoolList = res.data.data;
                } else {
                    layer.msg(msg.school.fetchListErr, {
                        'icon': 2
                    });
                }
            };
            schoolservice.getshoolList(param).then(suc);
        };


        $scope.model = function (cz, data) {
            var city;
            if (cz === 'add') {
                $scope.data.schoolForm = city = {
                    province: '',
                    city_name: '',
                    towns: ''
                };
                $scope.data.isedit = false;
                $scope.data.modeltitle = '添加';
            }
            if (cz === 'edit') {
                city = $filter('dressfilter')($scope.division, data.city);
                $scope.data.schoolForm = {
                    name: data.name,
                    number: data.number,
                    prefix: data.prefix,
                    address: data.address,
                    pk: data.pk,
                    city_name: city.city_name,
                    province: city.province,
                    towns: city.towns
                };
                $scope.data.isedit = true;
                $scope.data.modeltitle = '编辑';
            }
            if (cz === 'close') {
                feiboCommonFuncs.hideModal('setting-school-list');
                // $scope.data.schoolmodal.hide();
            } else {
                $timeout(function () {
                    $('#province').dropdown('set selected', "string:" + city.province);
                    $('#city').dropdown('set selected', "string:" + city.city_name);
                    $('#towns').dropdown('set selected', "string:" + city.towns);
                });
                $scope.data.schoolForm.parent_id = $scope.data.userInfo.school_id;
                // $scope.data.schoolmodal.show();
                feiboCommonFuncs.showModal('setting-school-list');
            }
        };


        $scope.saveSchool = function () {
            if (valiFrom.getVali($scope.data.valigroup.formId)) {
                var vs = $scope.data.schoolForm;
                var params = {
                    name: vs.name,
                    number: vs.number,
                    prefix: vs.prefix,
                    address: vs.address,
                    province: $scope.division[vs.province].name,
                    city_name: $scope.division[vs.province].cityList[vs.city_name].name,
                    towns: $scope.division[vs.province].cityList[vs.city_name].areaList[vs.towns]
                };
                if ($scope.data.schoolForm.pk) {
                    schoolservice.editSchool(params, $scope.data.schoolForm.pk).then(function (res) {
                        if (res.data.success) {
                            layer.msg(msg.school.editSuc, {
                                'icon': 1
                            });
                            $scope.model('close');
                            $scope.getShoolList();
                        } else {
                            layer.msg(msg.school.editErr, {
                                'icon': 2
                            });
                        }
                    });
                } else {
                    params.parent_id = $scope.data.userInfo.school_id;
                    schoolservice.addSchool(params).then(function (res) {
                        if (res.data.success) {
                            layer.msg(msg.school.addSuc, {
                                'icon': 1
                            });
                            $scope.model('close');
                            $scope.getShoolList();
                        } else {
                            layer.msg(msg.school.addErr, {
                                'icon': 2
                            });
                        }
                    });
                }
            }
        };

        $scope.delSchool = function (pk) {
            var suc = function (res) {
                if (res.data.success) {
                    layer.msg(msg.school.delSuc, {
                        'icon': 1
                    });
                    $scope.getShoolList();
                } else {
                    layer.msg(msg.school.delErr, {
                        'icon': 2
                    });
                }
            };
            layer.confirm('您确认要删除吗？', {
                btn: [Message.ok, Message.cancel] //按钮
            }, function () {
                schoolservice.delSchool(pk).then(suc);
            });

        };

        $scope.init();
    }
    //基础信息
    function schoolProfile($scope, $filter, schoolservice, userservice, valiFrom, feiboDrees, $timeout) {
        $scope.data = {
            readOnly: false,
            cityList: [],
            townsList: [],
            userInfo: {},
            shoolinfo: {},
            valigroup: {
                formId: 'setting-profile',
                group: 'setting',
                scope: 'profile'
            }
        };
        $scope.division = feiboDrees;


        $scope.saveshoolinfo = function () {
            if (valiFrom.getVali($scope.data.valigroup.formId)) {
                var scdata = $scope.data.shoolinfo;
                var params = {
                    name: scdata.name,
                    number: scdata.number,
                    address: scdata.address,
                    remark: scdata.remark,
                    official_website: scdata.official_website,
                    prefix: scdata.prefix,
                    domain: scdata.domain,
                    province: $scope.division[scdata.province].name,
                    city_name: $scope.division[scdata.province].cityList[scdata.city_name].name,
                    towns: $scope.division[scdata.province].cityList[scdata.city_name].areaList[scdata.towns]
                };
                var suc = function (res) {
                    if (res.data.success) {
                        layer.msg(msg.profile.editSuc, {
                            'icon': 1
                        });
                    } else {
                        layer.msg(msg.profile.editErr, {
                            'icon': 2
                        });
                    }
                };
                if ($scope.data.userInfo.school_id > 0) {
                    schoolservice.editSchool(params, scdata.pk).then(suc);
                } else {
                    schoolservice.addSchool(params).then(suc);
                }
            }
        };


        $scope.queryInit = function () {
            $('.good-good-study').popup({
                content: 'http:// 域名前缀 .121learn.com',
                variation: 'inverted'
            });
            $('.day-day-up').popup({
                content: '学号前缀 0001',
                variation: 'inverted'
            });
            //添加验证
            valiFrom.extenUniqueVali('uniquePrefix');
            valiFrom.addVali($scope.data.valigroup);
            $timeout(function () {
                $('#province').dropdown('set selected', $scope.data.shoolinfo.province);
                $('#city').dropdown('set selected', $scope.data.shoolinfo.city_name);
                $('#towns').dropdown('set selected', $scope.data.shoolinfo.towns);
            });
        };


        //初始化数据
        $scope.init = function () {
            var sd = $scope.data;
            userservice.getuserinfo().then(function (res) {
                if (res.data.success) {
                    sd.userInfo = res.data.data;
                    if (res.data.data.school_id > 0) {
                        sd.readOnly = true;
                    }
                    return schoolservice.getSingleShool(res.data.data.school_id);
                } else {
                    layer.msg(msg.user.fetLoginInfo, {
                        'icon': 2
                    });
                }
            }).then(function (res) {
                if (res.data.success) {
                    sd.shoolinfo = res.data.data;
                    sd.prefixreadOnly = sd.shoolinfo.prefix ? true : false;
                    var city = $filter('dressfilter')($scope.division, res.data.data.city);
                    sd.shoolinfo.province = city.province;
                    sd.shoolinfo.city_name = city.city_name;
                    sd.shoolinfo.towns = city.towns;
                    $scope.queryInit();
                } else {
                    layer.msg(msg.profile.fetchInfoErr, {
                        'icon': 2
                    });
                }
            });
        };
        $scope.init();
    }

    //头像
    function upphoto($scope, userservice, CommonService, $filter) {
        $scope.img = {
            userid: '',
            upimgpluin: '',
            avatar: '',
            oldsrc: ''
        };
        $scope.init = function () {
            userservice.getuserinfo().then(function (res) {
                if (res.data.success) {
                    return userservice.getUserById(res.data.data.id);
                } else {
                    layer.msg(msg.user.fetLoginInfo, {
                        'icon': 2
                    });
                }
            }).then(function (res) {
                if (res.data.success) {
                    $scope.img.avatar = $scope.img.oldsrc = $filter('absoluteUrl')(res.data.data.avatar);
                    $scope.img.userid = res.data.data.id;
                } else {
                    layer.msg(msg.personInfo.getUserinfoErr, {
                        'icon': 2
                    });
                }
            });
        };
        $scope.uploadMaterialCoverConfig = function () {
            var layerIndex;
            return {
                'FilesAdded': function (up, files) {
                    var reader = new FileReader();
                    reader.onload = function (event) {
                        $scope.img.avatar = event.target.result;
                        $scope.$apply();
                    };
                    reader.readAsDataURL(up.getFile(files[0].id).getNative());
                },
                'BeforeUpload': function () {
                    layerIndex = layer.load(1, {
                        shade: [0.1, '#fff'] //0.1透明度的白色背景
                    });
                },
                'FileUploaded': function (up, file, info) {
                    layer.close(layerIndex);
                    // var imgpath = encodeURI(up.getOption('domain') + JSON.parse(info).key);
                    var imgpath = JSON.parse(info).key;
                    $scope.img.oldsrc = imgpath;
                    $scope.edituser(imgpath);
                },
                'Error': function () {
                    layer.close(layerIndex);
                    layer.msg(Message.img.upLoadSizeErr + "2Mb", {
                        'icon': 2
                    });
                },
                'Key': function (up, file) {
                    /* eslint-disable */
                    var key = CryptoJS.MD5(file.name) + "_" + (new Date()).getTime();
                    return key;
                }
            };
        };


        $scope.img.upimgpluin = CommonService.upload2Qiniu('avatar-container', 'avatar-monitor',
            $scope.uploadMaterialCoverConfig, {
                max_file_size: '2mb',
                prevent_duplicates: false,
                mime_types: [{
                    title: "Image files",
                    extensions: "png,jpg,jpeg,gif"
                }]
            }, true);

        $scope.upimg = function () {
            $scope.img.upimgpluin.start();
        };


        $scope.imgcancel = function () {
            $scope.img.avatar = $scope.img.oldsrc;
        };


        $scope.edituser = function (url) {
            userservice.editUser({
                avatar: url
            }, $scope.img.userid).then(function (res) {
                if (res.data.success) {
                    $scope.img.oldsrc = url;
                    layer.msg(msg.personInfo.upAvatar.Suc, {
                        'icon': 1
                    });
                } else {
                    layer.msg(msg.personInfo.upAvatar.Err, {
                        'icon': 2
                    });
                }
            });
        };

        $scope.init();
    }

    //消息设置
    function notice($scope, noticeser, userservice) {
        $scope.data = {
            personInfo: {}
        };
        $scope.init = function () {
            userservice.getuserinfo().then(function (res) {
                if (res.data.success) {
                    $scope.data.personInfo = res.data.data;
                    return noticeser.getuserNoticeList(res.data.data.id);
                }
            }).catch(function (error) {
                console.error(error);
            });
        };
        $scope.init();
        $scope.news = function () {
            $('.check').click(function () {
                $(this).toggleClass('starcheck');
            });
        };
        $scope.news();
    }

    //激活邮箱
    function actionEmail($scope, userservice, $stateParams, $state) {
        $scope.param = {
            opk: $stateParams.pk,
            email: $stateParams.email,
            code: $stateParams.number
        };
        $scope.actionEmail = function () {
            userservice.actionEmail($scope.param).then(function (res) {
                if (res.data.success) {
                    layer.msg(msg.personInfo.actionEmail.Suc, {
                        'icon': 1
                    });
                    //跳转到个人信息设置
                    $state.go('uperset');
                } else {
                    layer.msg(msg.personInfo.actionEmail.Err, {
                        'icon': 2
                    });
                }
            });
        };
    }
}.call(this));
